import { DesktopOutlined, MoreOutlined, PlusOutlined } from "@ant-design/icons";
import { Button, Card, Form, List, Modal, Popover, Select, Space } from "antd";
import { useEffect, useState } from "react";
import { ClientInfo } from "./App";
import ConnectModal from "./components/ConnectModal";
import s from "./common.module.less";
import classNames from "classnames";
import { getConnectionApi, getShellApi, getToken } from "./utils/client";
import { getMinAppInfo } from "@linksaas-minapp/api";

export interface ClientPanelProps {
    curClientId: string;
    curShellId: string;
    clientList: ClientInfo[];
    onSelect: (clientId: string, shellId: string) => void;
    onChange: (clientList: ClientInfo[]) => void;
}

function ClientPanel(props: ClientPanelProps) {
    const [showConnectModal, setShowConnectModal] = useState(false);

    const [newTermType, setNewTermType] = useState("xterm");
    const [newTermClientId, setNewTermClientId] = useState("");

    const closeClient = async (clientId: string) => {
        const tmpList = props.clientList.filter(item => item.id != clientId);
        props.onChange(tmpList);
        const api = getConnectionApi();
        await api.connectionClosePost({
            connectionClosePostRequest: {
                token: getToken(),
                id: clientId,
            },
        });
        //处理curClientId
        if (clientId == props.curClientId) {
            if (tmpList.length == 0) {
                props.onSelect("", "");
            }
            for (const clientInfo of tmpList) {
                if (clientInfo.shellList.length > 0) {
                    props.onSelect(clientInfo.id, clientInfo.shellList[0].shellId ?? "");
                    return;
                }
            }
            props.onSelect(tmpList[0].id, "");
        }
    }

    const createShell = async () => {
        const tmpList = props.clientList.slice();
        const index = tmpList.findIndex(item => item.id == newTermClientId);
        if (index == -1) {
            return;
        }
        const api = getShellApi();
        const shellInfo = await api.shellOpenPost({
            shellOpenPostRequest: {
                token: getToken(),
                id: newTermClientId,
                termType: newTermType,
                width: 80,
                height: 40,
            },
        });
        tmpList[index].shellList.push(shellInfo);
        props.onChange(tmpList);
        if (props.curShellId == "") {
            props.onSelect(newTermClientId, shellInfo.shellId ?? "");
        }
        setNewTermClientId("");
    };

    useEffect(() => {
        const minAppInfo = getMinAppInfo();
        if (minAppInfo != undefined && minAppInfo.extraInfo != undefined && minAppInfo.extraInfo.length > 0) {
            setShowConnectModal(true);
        }
    }, []);

    return (
        <Card title="SSH连接"
            bordered={false} style={{ height: "50vh", overflowY: "hidden" }} bodyStyle={{ height: "calc(50vh - 60px)", overflowY: "auto", padding: "0px 0px" }}
            extra={
                <Space size="middle">
                    <Button type="text" style={{ minWidth: 0, padding: "0px 0px" }}
                        onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            setShowConnectModal(true);
                        }}>
                        <PlusOutlined />
                    </Button>
                </Space>
            }>
            <List rowKey="id" dataSource={props.clientList} renderItem={clientInfo => (
                <List.Item>
                    <Card title={clientInfo.name} style={{ border: "none", width: "100%" }}
                        bodyStyle={{ padding: "0px 0px", marginLeft: "20px" }}
                        extra={
                            <Space size="middle">
                                <Button type="text" style={{ minWidth: 0, padding: "0px 0px" }} onClick={e => {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    setNewTermType("xterm");
                                    setNewTermClientId(clientInfo.id);
                                }}><DesktopOutlined /></Button>
                                <Popover trigger="click" placement="bottom" content={
                                    <Space direction="vertical" size="small">
                                        <Button type="link" danger onClick={e => {
                                            e.stopPropagation();
                                            e.preventDefault();
                                            closeClient(clientInfo.id);
                                        }}>关闭连接</Button>
                                    </Space>
                                }>
                                    <MoreOutlined />
                                </Popover>
                            </Space>
                        }>
                        <List rowKey="shellId" dataSource={clientInfo.shellList} renderItem={shellInfo => (
                            <List.Item className={classNames(s.item, props.curShellId == shellInfo.shellId ? s.active : "")}>
                                <div className={s.name} onClick={e => {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    props.onSelect(clientInfo.id, shellInfo.shellId ?? "");
                                }}>
                                    <Space size="middle">
                                        <DesktopOutlined />
                                        <span title={`${props.curShellId}==${shellInfo.shellId}`}>{clientInfo.name}({shellInfo.shellIndex ?? 0})</span>
                                    </Space>
                                </div>
                            </List.Item>
                        )} />
                    </Card>
                </List.Item>
            )} />
            {showConnectModal == true && (
                <ConnectModal onOk={clientInfo => {
                    const tmpList = props.clientList.slice();
                    tmpList.push(clientInfo);
                    props.onChange(tmpList);
                    setShowConnectModal(false);
                    if (props.curShellId == "" && clientInfo.shellList.length > 0) {
                        props.onSelect(clientInfo.id, clientInfo.shellList[0].shellId ?? "");
                    }
                }} onCancel={() => setShowConnectModal(false)} />
            )}
            {newTermClientId != "" && (
                <Modal open title="打开终端" onCancel={e => {
                    e.stopPropagation();
                    e.preventDefault();
                    setNewTermClientId("");
                }} onOk={e => {
                    e.stopPropagation();
                    e.preventDefault();
                    createShell();
                }}>
                    <Form>
                        <Form.Item label="终端类型">
                            <Select options={[
                                {
                                    label: "xterm",
                                    value: "xterm",
                                },
                                {
                                    label: "xterm-r6",
                                    value: "xterm-r6",
                                },
                                {
                                    label: "xterm-256color",
                                    value: "xterm-256color",
                                },
                                {
                                    label: "vt100",
                                    value: "vt100",
                                },
                                {
                                    label: "vt220",
                                    value: "vt220",
                                },
                                {
                                    label: "vt400",
                                    value: "vt400",
                                },
                                {
                                    label: "vt900",
                                    value: "vt900",
                                },
                            ]} value={newTermType} onChange={value => setNewTermType(value)} />
                        </Form.Item>
                    </Form>
                </Modal>
            )}
        </Card>
    );
}

export default ClientPanel;